package com.example.demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        String uri=httpServletRequest.getRequestURI();
//        System.out.println(uri);
        HttpSession session=httpServletRequest.getSession(true);
        if (uri.contains("login")||session.getAttribute("user")!=null||uri.contains("register")||uri.contains("findpassword")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            servletRequest.setAttribute("msg","请先登录");
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }


}
